package factory

import (
	"fmt"
	"simple-http-server/store"
	"sync"
)

var (
	bookRepositoryFactoryMu    sync.RWMutex
	bookStoreRepositoryStorage = make(map[string]store.BookRepository)
)

func RegisterBookRepository(name string, bookRepository store.BookRepository) {
	bookRepositoryFactoryMu.Lock()
	defer bookRepositoryFactoryMu.Unlock()
	if bookRepository == nil {
		panic("store repository is nil")
	}
	if _, dup := bookStoreRepositoryStorage[name]; dup {
		panic("store repository call Register twice for provider" + name)
	}
	bookStoreRepositoryStorage[name] = bookRepository
}

func NewBookRepository(name string) (store.BookRepository, error) {
	bookRepositoryFactoryMu.RLock()
	defer bookRepositoryFactoryMu.RUnlock()
	repository, ok := bookStoreRepositoryStorage[name]
	if !ok {
		return nil, fmt.Errorf("store repository unknown,name %s", name)
	}
	return repository, nil
}
